//
//  BRSelectCityViewController.m
//  carcareIOS
//
//  Created by 王然 on 16/8/3.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "BRSelectCityViewController.h"
#import "BRChoiceCityCell.h"
#import "BRSelectCityCell.h"
#import "BRSelectCityRightCell.h"


#define CELL_GRAY_HEIGHT 35


@interface BRSelectCityViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSIndexPath * selectIndexPath;
}
@property (nonatomic ,strong) UITableView * leftTableView;

@property (nonatomic ,strong) UITableView * rightTableView;

@property (nonatomic , strong) UIView * blackView;

@property (nonatomic , copy) NSArray <VioCityModel *>* provinceArray;

@property (nonatomic , strong) NSMutableArray * clickArray;

@property (nonatomic , strong) NSMutableArray * rememberClickIndexArray;//被点击的的cell的点击的cell 若为1 则为被选中 否则 为未被选中

@end

@implementation BRSelectCityViewController

- (instancetype)initWithData:(NSArray <VioCityModel *>*)provinceArray clickCityData:(NSArray *)clickData
{
    self = [super init];
    if (self) {
        self.provinceArray = [NSArray arrayWithArray:provinceArray];
        self.clickArray = [NSMutableArray arrayWithArray:clickData];
        [self reloadArray];
        [self.leftTableView reloadData];
    }
    
    return self;
}
- (void)reloadArray
{
    NSMutableArray * tempProvinceArr = [NSMutableArray arrayWithCapacity:self.provinceArray.count];
    for (int index = 0; index < self.provinceArray.count; index ++) {
        VioCityModel * model = [self.provinceArray objectAtIndex:index];
        
        VioCityClickModel * clickIndexModel = [[VioCityClickModel alloc]init];
        for (VioCityModel * clickProvinceModel in self.clickArray) {
            if (model.cid == clickProvinceModel.cid ) {
                clickIndexModel.isClick = YES;
            }
        }
        if (model.hasSubCities) {//有子城市
            clickIndexModel.hasSubCities = YES;
            NSMutableArray * tempCityArr = [NSMutableArray arrayWithCapacity:model.subcities.count];
            for (int cityIndex = 0; cityIndex < model.subcities.count; cityIndex ++) {
                VioCityModel * cityModel = model.subCityModels[cityIndex];
                VioCityClickModel * clickCityIndexModel = [[VioCityClickModel alloc]init];
                clickCityIndexModel.hasSubCities = cityModel.hasSubCities;
                for (VioCityModel * clickCityModel in self.clickArray) {
                    if (cityModel.cid == clickCityModel.cid) {
                        clickIndexModel.isClick = YES;
                        clickCityIndexModel.isClick = YES;
                    }
                }
                [tempCityArr addObject:clickCityIndexModel];
            }
            clickIndexModel.clickSubCitys = [NSArray arrayWithArray:tempCityArr];
            
        }else//无子城市
        {
            clickIndexModel.hasSubCities = NO;
            clickIndexModel.clickSubCitys = [NSArray array];
        }
        [tempProvinceArr addObject:clickIndexModel];
    }
    self.rememberClickIndexArray = [NSMutableArray arrayWithArray:tempProvinceArr];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"查询城市";
    
    [self createTableView];
     __weak __typeof(self) wself = self;

    [self navSetupRightTitle:@"保存" action:^{
        if ([wself.delegate respondsToSelector:@selector(configClickCityModels:)]) {
            [wself.delegate configClickCityModels:wself.clickArray];
        }
        [wself.navigationController popViewControllerAnimated:YES];
    }];

    self.blackView = [[[UIView viewWithFrame:CGRectMake(0, 0, BLACK_VIEW_WIDTH, __MAIN_HEIGHT_64)] resetBackgroundColor:COLOR_RGBA(0, 0, 0, 0.4)] setupOnView:self.view];
    self.blackView.hidden = YES;
    
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick)];
    [self.blackView addGestureRecognizer:tapGesture];
}
- (void)createTableView
{
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, __MAIN_WIDTH , __MAIN_HEIGHT_64) style:UITableViewStylePlain];
    self.leftTableView.backgroundColor = [Theme backGroundColor];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorColor = [UIColor clearColor];
    self.leftTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:self.leftTableView];
    
    self.rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(__MAIN_WIDTH, 0, SMALL_TABLEVIEW_WIDTH ,__MAIN_HEIGHT_64) style:UITableViewStylePlain];
    self.rightTableView.backgroundColor = [Theme backGroundColor];
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    self.rightTableView.separatorColor = [UIColor clearColor];
    self.rightTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:self.rightTableView];
}
#pragma mark - tableview delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (tableView == self.leftTableView ? self.titleArray.count : 1);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section != 5 && tableView == self.leftTableView ) {
        return [self.titleArray[section] count];
    }
    NSInteger rightTabelViewCount = 0;
    if (selectIndexPath) {
        
        VioCityModel * model = [self.provinceArray objectAtIndex:selectIndexPath.row];
        rightTabelViewCount  = [model.subcities count];
    }
    
    return (tableView == self.leftTableView ? (self.provinceArray.count) : (rightTabelViewCount));
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (tableView == self.leftTableView ? ((indexPath.section == 0 || indexPath.section == 2 || indexPath.section == 4 ) ? (indexPath.section == 2 ? 0 : CELL_GRAY_HEIGHT) : (indexPath.section == 3 ? 0 : [BRSelectCityCell getCellHeight])) : [BRSelectCityRightCell getCellHeight]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell ;
    
    if (tableView == self.leftTableView) {
        switch (indexPath.section) {
            
            case 1:
            {
                NSString * cellID = @"cellLeftOnCityID";
                cell = [tableView dequeueReusableCellWithIdentifier:cellID];
                if (!cell) {
                    cell = [[BRChoiceCityCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
                    
                }
                __weak __typeof(self) wself = self;
                [((BRChoiceCityCell *)cell)reloadChoiceCitys:self.clickArray clickIndex:^(NSInteger index) {
                    [wself removeClickArrayWithIndex:index];
                    [wself.clickArray removeObjectAtIndex:index];
                    [wself.leftTableView reloadData];
                }];
            }
                break;
            case 3:
            {
                NSString * cellID = @"cellLeftLocCityID";
                cell = [tableView dequeueReusableCellWithIdentifier:cellID];
                if (!cell) {
                    cell = [[BRSelectCityCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
                }
                [((BRSelectCityCell *)cell) reloadTitle:@"" isClick:NO rightClickImageVShow:NO];
                ((BRSelectCityCell *)cell).isHiddenLine = YES;
            }
                break;
            case 5:
            {
                NSString * cellID = @"cellLeftProvinceListID";
                cell = [tableView dequeueReusableCellWithIdentifier:cellID];
                if (!cell) {
                    cell = [[BRSelectCityCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
                }
                VioCityModel * model = [self.provinceArray objectAtIndex:indexPath.row];
                
                VioCityClickModel * clickModel = self.rememberClickIndexArray[indexPath.row];
                
                [((BRSelectCityCell *)cell) reloadTitle:model.name isClick:clickModel.isClick rightClickImageVShow:model.subcities.count > 0];
                ((BRSelectCityCell *)cell).isHiddenLine = NO;
                
               

            }
            break;
            case 0:
            case 2:
            case 4:
            {
                NSString * cellID = @"cellLeftTextID";
                cell = [tableView dequeueReusableCellWithIdentifier:cellID];
                if (!cell) {
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
                    cell.backgroundColor = [Theme backGroundColor];
                    [cell resetBorderWidth:0.5 borderColor:[Theme lineColor]];
                    
                    CGFloat labelX = 14 * __MAIN_RATIO_375;
                    [[UILabel labelWithFrame:CGRectMake(labelX, 9, __MAIN_WIDTH - labelX * 2, 20) font:FONT_DEFAULT_Light(13) text:@"" textColor:COLOR_HEXSTRING(@"#bdbdbd")] setupOnView:cell].tag = 10010;
                }
                UILabel * textL = (UILabel *)[cell viewWithTag:10010];
                textL.text = self.titleArray[indexPath.section][indexPath.row];
            }
                break;
            default:
                break;
        }
    }else
    {
        NSString * cellID = @"cellRightID";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[BRSelectCityRightCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        if (selectIndexPath) {
            VioCityModel * model = [self.provinceArray objectAtIndex:selectIndexPath.row];
             VioCityModel * cityModel = model.subCityModels[indexPath.row];
            VioCityClickModel * clickModel = self.rememberClickIndexArray[selectIndexPath.row];
            VioCityClickModel * clickCityModel = clickModel.clickSubCitys[indexPath.row];
            
            [((BRSelectCityRightCell *)cell) reloadTitle:cityModel.name isClick:clickCityModel.isClick];
        }
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark - 删除上面某一个选中的数组中的元素 坐标index
- (void)removeClickArrayWithIndex:(NSInteger)index
{
    VioCityModel * removeModel = self.clickArray[index];
    
    for (NSInteger index = 0; index < self.provinceArray.count; index ++) {
        VioCityClickModel * clickIndexModel = self.rememberClickIndexArray[index];
        VioCityModel * model = self.provinceArray[index];
        if (removeModel.cid == model.cid) {
            clickIndexModel.isClick = NO;
            return;
        }else if(model.canChoice)
        {
            for (int cityIndex = 0 ; cityIndex < model.subCityModels.count; cityIndex ++) {
                NSInteger clickCount = 0;
                VioCityModel * cityModel = model.subCityModels[cityIndex];
                for (VioCityModel * newClickModel in self.clickArray) {
                    if (cityModel.pid == newClickModel.pid) {
                        clickCount ++;
                    }
                }
                if (clickCount < 2) {
                    clickIndexModel.isClick = NO;
                }
                if (cityModel.cid == removeModel.cid) {
                    VioCityClickModel * clickCityIndexModel = clickIndexModel.clickSubCitys[cityIndex];
                    clickCityIndexModel.isClick = NO;
                    return;
                }
            }
        }
    }

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.leftTableView) {
        if (indexPath.section == 5) {
            
            VioCityModel * model = [self.provinceArray objectAtIndex:indexPath.row];
            if (model.hasSubCities) {
                
                if (!selectIndexPath)
                {
                    selectIndexPath = nil;
                }
                selectIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
                
                [self.blackView setHidden: NO];
                
                [self.rightTableView reloadData];
                __weak __typeof(self)wself = self;
                [UIView animateWithDuration:0.2 animations:^{
                    __strong __typeof(wself) strongSelf = wself;
                    [strongSelf -> _rightTableView setFrame:CGRectMake(BLACK_VIEW_WIDTH, 0, SMALL_TABLEVIEW_WIDTH, __MAIN_HEIGHT_64)];
                }];
            }
            else
            {
                VioCityClickModel * clickModel = self.rememberClickIndexArray[indexPath.row];
                if (model.canChoice) {
                    if (clickModel.isClick) {
                        for (VioCityModel * removeClickModel in self.clickArray) {
                            if (removeClickModel.cid == model.cid) {
                                [self.clickArray removeObject:removeClickModel];
                                break;
                            }
                        }
//                        [self.clickArray removeObject:model];
                    }else
                    {
                        [self.clickArray addObject:model];
                    }
                    clickModel.isClick = !clickModel.isClick;
                    [self.leftTableView reloadData];
                }else [AlertMgr showShortTextTips:@[[NSString stringWithFormat:@"很抱歉，%@暂不支持该功能",model.name]]];
            }
        }
    }else if(tableView == self.rightTableView)
    {
        
        VioCityModel * model = [self.provinceArray objectAtIndex:selectIndexPath.row];
        VioCityModel * cityModel = model.subCityModels[indexPath.row];
        
        VioCityClickModel * clickModel = [self.rememberClickIndexArray objectAtIndex:selectIndexPath.row];
        VioCityClickModel * clickCityModel = clickModel.clickSubCitys[indexPath.row];
        if (cityModel.canChoice) {
            if (clickCityModel.isClick) {//如果已经被选择了  则执行取消功能
                NSInteger clickCount = 0;
                for (VioCityModel * clickModel in self.clickArray) {
                    if (cityModel.canChoice && cityModel.pid == clickModel.pid) {
                        clickCount ++;
                    }
                }
                if (clickCount < 2) {
                    clickModel.isClick = NO;
                }
                for (VioCityModel * removeClickModel in self.clickArray) {
                    if (removeClickModel.cid == cityModel.cid) {
                        [self.clickArray removeObject:removeClickModel];
                        break;
                    }
                }
//                [self.clickArray removeObject:cityModel];
                
            }else//直接执行选择操作 并添加到选择的model数组中
            {
                clickModel.isClick = YES;
                [self.clickArray addObject:cityModel];
            }
            clickCityModel.isClick = !clickCityModel.isClick;
            
            [self.leftTableView reloadData];
            [self.rightTableView reloadData];
        }else [AlertMgr showShortTextTips:@[[NSString stringWithFormat:@"很抱歉，%@暂不支持该功能",cityModel.name]]];
//        [self tapGestureClick];
        
    }

    
}

- (void)tapGestureClick
{
    [self.blackView setHidden: YES];
    __weak __typeof(self)wself = self;
    [UIView animateWithDuration:0.2 animations:^{
        __strong __typeof(wself) strongSelf = wself;
        [strongSelf -> _rightTableView setFrame:CGRectMake(__MAIN_WIDTH, 0, SMALL_TABLEVIEW_WIDTH, __MAIN_HEIGHT_64) ];
    }];
}
- (NSArray *)titleArray
{
    //@"当前定位"
    return @[@[@"所选城市"],@[@"所选城市列表"],@[@""],@[@"当前定位城市列表"],@[@"所有城市"],@[@"所有城市列表"]];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
